package cmd

import (
	"fmt"
	"io/ioutil"
	"net"

	"gitee.com/shaddy/k3sinstall/install"
	"gitee.com/shaddy/k3sinstall/mylog"
	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"
)

var (
	AddNode []string
	addCmd  = &cobra.Command{
		Use:   "add",
		Short: "Simplest way to add node to your k3s HA cluster",
		Long:  `k3sinstall add --node`,
		Run: func(cmd *cobra.Command, args []string) {
			y, err := ioutil.ReadFile(ConfigFile)
			if err != nil {
				mylog.Error.Panicf("read config file %s failed %w", ConfigFile, err)
			}
			config := &install.K3sConfig{}
			err = yaml.Unmarshal(y, config)
			if err != nil {
				mylog.Error.Panicf("unmarshal config file failed: %w", err)
			}

			if len(AddNode) == 0 {
				mylog.Error.Panic("err no node arg !!!")
				cmd.Help()
			} else {
				for k := range AddNode {
					ip, port, err := parseIpPort(AddNode[k])
					if err != nil {
						mylog.Error.Panicf("解析ip地址失败 ip: %s port: %d  %s /n", ip, port, err.Error())
					}
					ipaddress := net.ParseIP(ip)
					if ipaddress == nil {
						mylog.Error.Panicf("解析ip地址失败 请确认node参数并指定正确格式的ip地址 ip: %s port %d \n", ip, port)

					}
					if port < 1 || port > 65535 {
						mylog.Error.Panicf("解析ip地址失败 请确认node参数并指定正确格式的ip地址 ip: %s port %d \n", ip, port)
					}
					AddNode[k] = fmt.Sprintf("%s:%d", ipaddress.String(), port)
				}

				install.AddHookNodes(config, AddNode)

			}

		},
		PreRun: func(cmd *cobra.Command, args []string) {
			home, err := Home()
			if err != nil {
				mylog.Error.Panicf("获取Home目录失败 %s", err.Error())
			}
			ConfigHome = home
			if !FileExist(home + "/.k3sinstall") {
				mylog.Error.Panicf("can not find config file , is install k3s cluster ?")

			}
			ConfigFile = home + "/.k3sinstall/config.yaml"
		},
	}
)

func init() {
	addCmd.Flags().StringSliceVar(&AddNode, "node", []string{}, "add nodes")
}
